import React, {Component} from 'react'
import {
    Animated,
    DeviceEventEmitter,
    Dimensions,
    Easing,
    Image,
    ListView,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableHighlight,
    TouchableOpacity,
    View
} from "react-native";
import StyleUtils from "../../res/styles/StyleUtils";
import Navigation from "../../custom/Navigation";
import ConfirmOrderListItem from "./ConfirmOrderListItem";
import ViewUtils from "../../utils/ViewUtils";
import ShippingMethodPage from "./ShippingMethodPage";
import CommonUtils from "../../common/CommonUtils";
import AddressPage from "../mePage/address/AddressPage";
import IparNetwork, {SERVER_TYPE} from "../../httpUtils/IparNetwork";
import OrderPayPage from "../mePage/order/OrderPayPage";
import I18n from "../../res/language/i18n";
import RegionsIcon from "../../common/RegionsIcon";
import AlertDialog from "../../custom/AlertDialog";
import ModalBottomUtils from "../../utils/ModalBottomUtils";
import BottomSelectionBox from "../../utils/BottomSelectionBox";

let height = Dimensions.get('window').height;
let onClickTypes = {
    shippingMethod: 'shipping Method',
    submit: 'Submit',
    shippingAddress: 'shipping-Address',
    warehouse: 'warehouse',
};

let ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2
});
export default class ConfirmOrderPage extends Component {

    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();
        this.country;


        this.state = {
            dataSource: ds.cloneWithRows(this.props.dataSource.data),
            fadeAnim: new Animated.Value(120),
            rotation: new Animated.Value(0),
            isOpen: true,
            shippingMethodData: I18n.t('default.selectShippingMethod'),
            shippingAddressData: I18n.t('default.chooseReceivingAddress'),
            currency_code: this.props.currencyInfo.currency_code,
            swap_amount: this.props.currencyInfo.swap_amount,
            loading: false,
            toastAlert: false,
            modalVisible: false,
            userInfo: {},
            wareHouseGoodsData: [],
            currencyCode: this.props.currencyInfo.currency_code,
            currncyName: this.props.currencyInfo.currency_name,
            shippingAmount: 0,
            explain: '',
        }
    }

    componentDidMount() {
        this.getCountryInfo();
        this.getUserInfo()
    }


    /**
     * 获取用户的默认收获地址
     * @param user_id
     */
    getUserDefAddress(user_id) {

        this.showLoading(true);
        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'useraddress/getDef?',
            'user_id=' + user_id)
            .then((result) => {
                this.showLoading(false);
                if (result.code !== 0) {
                    this.setState({
                        shippingAddressData: result,
                    });
                }
            })
            .catch(() => {
                this.showLoading(false);
            })
    }

    /**
     * 获取国家编号
     */
    getCountryInfo() {
        CommonUtils.getAcyncInfo('country_iso')
            .then((result) => {
                this.country = result;
            })
    }

    /**
     * 获取用户信息
     */
    getUserInfo() {
        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                if (result) {
                    let parse = JSON.parse(result);
                    this.getUserDefAddress(parse.main_user_id);
                    this.setState({
                        userInfo: parse,
                    })
                }
            });
    }

    /**
     * 动画open&&close
     */
    startAnimation() {
        let animValue = height / 2.5;
        let rotationValue = 1;
        // let animValue = 112 * dataArray.length;
        if (!this.state.isOpen) {
            animValue = 120;
            rotationValue = 0;
        }
        Animated.timing(       // 随时间变化而执行的动画类型
            this.state.fadeAnim,   // 动画中的变量值
            {
                toValue: animValue,   // 透明度最终变为1，即完全不透明
                duration: 500, // 动画时间
            },
        ).start();
        Animated.timing(       // 随时间变化而执行的动画类型
            this.state.rotation,   // 动画中的变量值
            {
                toValue: rotationValue,   // 透明度最终变为1，即完全不透明
                duration: 500, // 动画时间
            }
        ).start();


        this.setState({
            isOpen: !this.state.isOpen
        })
    }


    /**
     * 获取实体店数据(产品有的。。)
     */
    getGoodsWareHouseData() {
        if (this.state.wareHouseGoodsData.length > 0) {
            this.setState({
                modalVisible: true
            });
            return;
        }

        let goodsData = [];
        for (goods of this.props.dataSource.data) {
            if (goods.is_suite === 1) {
                for (let suiteGoodsId of goods.items.split(',')) {
                    goodsData.push({
                        "goods_id": suiteGoodsId,
                        "size": 1
                    });
                }
            } else {
                goodsData.push({
                    "goods_id": goods.goods_id,
                    "size": goods.goods_number
                });
            }
        }
        let data = {
            "country": this.state.userInfo ? this.state.userInfo.country : 'null',
            "item": goodsData,
            "is_pickup": 1,
        };
        CommonUtils.showLoading();
        this.iparNetwork.getPostJson(SERVER_TYPE.goods + 'wareGoods?', data)
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    this.setState({
                        modalVisible: true,
                        wareHouseGoodsData: result.data,
                    });
                } else {
                    alert(I18n.t('o.isNotAvailableForPickup'))
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('ConfirmOrderPage---getGoodsWareHouseData--error:' + error);
            })
    }


    onClick(type) {
        switch (type) {
            case onClickTypes.shippingMethod://快递方式


                if (!this.state.shippingAddressData.id) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.chooseReceivingAddress'));//请选择收货地址
                    return
                }
                this.props.navigator.push({
                    component: ShippingMethodPage,
                    params: {
                        dataSource: this.props.dataSource.data,
                        swap_amount: this.state.swap_amount,
                        shippingAddressData: this.state.shippingAddressData,
                        currencyInfo: this.props.currencyInfo,
                        origin: this.props.dataSource.data[0].country,
                        callback: (shippingData, resultData, shippingAmount) => {
                            if (!shippingData) return;
                            this.isPickup = 0;
                            let _shippingAmount = 0;
                            if (shippingData.expressService === 'china_post') {
                                if (this.country === 'CN' && this.getSubTotal(1) <= 69) {
                                    _shippingAmount = 10
                                }
                            } else if (shippingData.expressService === 'pic_up') {
                                this.isPickup = 1
                            } else {
                                _shippingAmount = shippingAmount
                            }

                            this.setState({
                                shippingAmount: _shippingAmount,
                                explain: resultData ? resultData.explain : null,
                                shippingMethodData: shippingData,
                            });


                        }
                    }
                });

                break;
            case onClickTypes.shippingAddress://收获地址
                this.props.navigator.push({
                    component: AddressPage,
                    params: {
                        selectAddressId: this.state.shippingAddressData.id,
                        callback: (dataArray) => {
                            this.setState({
                                shippingAddressData: dataArray ? dataArray : I18n.t('default.chooseReceivingAddress'),
                                shippingAmount: 0.0,
                                shippingMethodData: I18n.t('default.selectShippingMethod'),
                            })
                        }
                    }
                });
                break;
            case onClickTypes.submit:
                if (this.isPickup === null) {
                    DeviceEventEmitter.emit('toast', I18n.t('RT.receivingMethod'));//请选择收货地址
                    return
                }


                if (!this.state.shippingAddressData.id) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.chooseReceivingAddress'));
                    this.onClick(onClickTypes.shippingAddress);
                    return
                }
                if (!this.state.shippingMethodData.id) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.selectShippingMethod'));
                    this.onClick(onClickTypes.shippingMethod);
                    return
                }

                if (this.isPickup === 1 && !this.selectWareHouse) {
                    DeviceEventEmitter.emit('toast', I18n.t('RT.receivingPickingMethod'));
                    this.onClick(onClickTypes.warehouse);
                    return;
                }
                this.submit();
                break;
            case onClickTypes.warehouse:
                this.getGoodsWareHouseData();
                break;

        }
    }


    showLoading(visible) {
        if (visible) {
            CommonUtils.showLoading();
        } else {
            CommonUtils.dismissLoading();
        }
    }


    /**
     * 下单
     */
    submit() {
        this.showLoading(true);

        let dataSource = this.props.dataSource;
        let userInfo = this.state.userInfo;
        let shippingAddressData = this.state.shippingAddressData;
        let shippingMethodData = this.state.shippingMethodData;

        //order_type
        let _order_type = 3;
        if (dataSource.order_type === 'order') {
            _order_type = 2
        } else if (dataSource.order_type === 'integral') {
            _order_type = 4
        }


        //cart_ids
        let cart_id = '';
        for (let i = 0, len = dataSource.data.length; i < len; i++) {
            cart_id = cart_id + dataSource.data[i].cart_id + ','
        }


        let formData = new FormData();
        formData.append("cart_id", cart_id);
        formData.append("user_id", userInfo.user_id);
        formData.append("order_type", _order_type);

        formData.append("address_id", shippingAddressData.addressId);
        formData.append("consignee", shippingAddressData.userName);
        formData.append("consignee_mobile", shippingAddressData.mobile);
        formData.append("address", shippingAddressData.address);

        formData.append("express_id", shippingMethodData.id);
        formData.append("express_name", shippingMethodData.name);

        formData.append("froms", Platform.OS === 'ios' ? 'IOS' : 'Android');
        formData.append("country", this.country);
        formData.append("swap_amount", this.props.currencyInfo.swap_amount);
        formData.append("shipping_amount", this.isPickup === 1 ? 0 : this.state.shippingAmount);
        formData.append("import_tax", 0);

        formData.append("is_pickup", this.isPickup);
        formData.append("warehouse_id", this.isPickup === 1 ? this.selectWareHouse.warehouse_id : null);
        formData.append("warehouse_name", this.isPickup === 1 ? this.selectWareHouse.name : null);


        // 请求
        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + 'saveOrder', formData)
            .then((result) => {
                this.showLoading(false);
                if (result.code === 200) {
                    DeviceEventEmitter.emit('isOrder');
                    DeviceEventEmitter.emit('isBuyGoods');
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    this.props.navigator.push({
                        component: OrderPayPage,
                        name: 'OrderPayPage',
                        params: {
                            orderData: result.data,
                            type: 'confirmOrder'
                        }
                    })
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                    console.log(result);
                }
            })
            .catch((error) => {
                this.showLoading(false);
                console.log('ConfirmOrderPage--submit---error', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
            })

    }


    /**
     * 计算总额
     * @param type 0=>subTotal 1=>pay amount
     * @returns {number}
     */
    getSubTotal(type) {
        let dataSource = this.props.dataSource.data;
        let commonUtils = new CommonUtils();

        let swapAmount = this.state.swap_amount;
        let subTotal = 0;

        for (let i = 0, len = dataSource.length; i < len; i++) {
            let _payAmount = 0;//ibm 价格
            let goodsInfo = dataSource[i];
            if (type === 1) {
                _payAmount = (commonUtils.getPercentOwnAmount(this.state.userInfo,goodsInfo, swapAmount));
                if (_payAmount <= 0) {
                    _payAmount = (goodsInfo.goods_pv * swapAmount);
                }
            } else {
                _payAmount = (goodsInfo.goods_pv * swapAmount);
            }

            subTotal += (_payAmount) * goodsInfo.goods_number

        }
        return subTotal
    }

    render() {
        /**
         * 如果还没选择收货地址的话直接写shippingAddressData
         * */
        let shippingAddressData = this.state.shippingAddressData;
        let shippingAddressText = shippingAddressData.id ?
            I18n.t('default.receiver') + ': ' + shippingAddressData.userName + '\n' +
            I18n.t('default.mobile') + ': ' + shippingAddressData.mobile + '\n' +
            I18n.t('default.address') + ': ' + shippingAddressData.address : shippingAddressData;


        let shippingMethodData = this.state.shippingMethodData;
        let shippingMethodText = shippingMethodData.id ?
            shippingMethodData.name : shippingMethodData;
        let subTotal = this.getSubTotal(0);
        let paySubTotal = this.getSubTotal(1);
        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    title={I18n.t('default.confirmOrder')}
                />

                {/**view box*/}
                <ScrollView style={{padding: 16}}>

                    {/**Shipping Address title*/}
                    <Text style={[styles.title, StyleUtils.smallFont]}>{I18n.t('default.shippingAddress')}</Text>

                    {/**Shipping Address view*/}
                    <TouchableOpacity
                        onPress={() => this.onClick(onClickTypes.shippingAddress)}
                        style={[StyleUtils.justifySpace, StyleUtils.marginTop, styles.border]}>

                        <Text
                            numberOfLines={3}
                            style={[StyleUtils.smallFont, {
                                color: '#333333',
                                marginTop: 4,
                                marginBottom: 4,
                                paddingLeft: 0,
                                lineHeight: 22,
                                flex: 1,
                            }]}>
                            {shippingAddressText}

                        </Text>

                        <Image
                            style={[StyleUtils.tabIconSize, {tintColor: '#c7cbcd'}]}
                            source={require('../../res/images/ic_right_more.png')}/>
                    </TouchableOpacity>

                    {/**your orders*/}
                    <Text
                        style={[styles.title, StyleUtils.smallFont, {marginTop: 22}]}>{I18n.t('default.orderDetail')}</Text>
                    {this.props.dataSource.order_type !== 'order' ?
                        <View style={[StyleUtils.rowDirection, StyleUtils.marginTop, {alignItems: 'center'}]}>
                            <Image
                                resizeMode="contain"
                                style={{height: 14, width: 22, marginBottom: 8, resizeMode: 'contain'}}
                                source={new RegionsIcon().getIcons(this.props.dataSource.order_type)}/>
                            <Text
                                style={[StyleUtils.text, StyleUtils.smallFont, {paddingTop: 0}]}>{this.goodsCountry(this.props.dataSource.order_type)}</Text>
                        </View> : null
                    }
                    <Animated.View
                        style={{height: this.state.fadeAnim}}
                    >
                        <ListView
                            dataSource={this.state.dataSource}
                            renderRow={(rowData, sectionID, rowID) => this.renderRow(rowData, rowID)}
                        />
                    </Animated.View>
                    <TouchableHighlight
                        onPress={() => this.startAnimation()}
                        underlayColor={'#d9dadb'}
                        activeOpacity={0.7}
                        style={[StyleUtils.center, {padding: 4, backgroundColor: '#f3f4f5'}]}>

                        <Animated.View
                            style={{
                                transform: [{
                                    rotateZ: this.state.rotation.interpolate({
                                        inputRange: [0, 1],
                                        outputRange: ['0deg', '180deg']
                                    })
                                }]
                            }}>
                            <Image
                                roundAsCircle={true}
                                style={[StyleUtils.tabIconSize, {tintColor: '#727476'},]}
                                source={require('../../res/images/ic_more.png')}/>
                        </Animated.View>

                    </TouchableHighlight>

                    <Text
                        style={[styles.defaultTv, StyleUtils.smallFont, {marginTop: 22}]}>{I18n.t('default.shippingMethod')}</Text>

                    {ViewUtils.getButtunMenu(shippingMethodText, () => this.onClick(onClickTypes.shippingMethod), [StyleUtils.marginTop])}
                    {this.isPickup === 1 && ViewUtils.getButtunMenu(this.selectWareHouse ? this.selectWareHouse.name : I18n.t('RT.receivingAddress'), () => this.onClick(onClickTypes.warehouse), [StyleUtils.marginTop])}

                    <Text style={[styles.defaultTv, StyleUtils.smallFont]}>{I18n.t('default.orderTotalAmount')}</Text>

                    {ViewUtils.getDoubleTv(I18n.t('default.subtotal'), subTotal.toFixed(1) + ' ' + this.state.currencyCode)}
                    {ViewUtils.getDoubleTv(I18n.t('default.savings'), (subTotal - paySubTotal).toFixed(1) + ' ' + this.state.currencyCode)}
                    {ViewUtils.getDoubleTv(I18n.t('default.shippingCost'), (this.isPickup === 1 ? 0 : this.state.shippingAmount.toFixed(1)) + ' ' + this.state.currencyCode)}
                    {ViewUtils.getDoubleTv(I18n.t('default.vat'), 0)}
                    {ViewUtils.getDoubleTv(I18n.t('default.importTaxIf'), 0)}
                    <View style={[StyleUtils.flex, StyleUtils.center, StyleUtils.rowDirection, {
                        marginTop: 16,
                        marginBottom: '35%'
                    }]}>
                        <Text style={[StyleUtils.flex, StyleUtils.smallFont, {
                            color: '#202020',
                            fontSize: 17,
                            textAlign: 'left',
                        }]}>{I18n.t('default.total')}</Text>
                        <Text style={[StyleUtils.flex, StyleUtils.smallFont, {
                            textAlign: 'right',
                            color: '#343434',
                            fontSize: 17
                        }]}>
                            {(paySubTotal + (this.isPickup === 1 ? 0 : this.state.shippingAmount)).toFixed(1) + ' ' + this.state.currencyCode}
                        </Text>
                    </View>

                </ScrollView>
                <View style={styles.btnBox}>
                    {ViewUtils.getButton(I18n.t('default.submit'), () => this.onClick(onClickTypes.submit))}
                </View>
                <AlertDialog
                    centerSts={I18n.t('default.ok')}
                    singleBtnOnclick={() => {
                        this.setState({
                            toastAlert: false,
                        })
                    }}
                    contentTv={I18n.t('toast.isErrorShippingAddress')}
                    visible={this.state.toastAlert}
                    requestClose={() => this.setState({
                        toastAlert: false,
                    })}
                />

                <ModalBottomUtils
                    visible={this.state.modalVisible}
                    renderRow={(rowData, s, index) => this.renderModalItem(rowData, index)}
                    requestClose={() => {
                        this.setState({modalVisible: false})
                    }}
                    dataSource={ds.cloneWithRows(this.state.wareHouseGoodsData)}
                    title={I18n.t('RT.selectWareHouse')}/>


            </View>
        )
    }


    /**
     * renderModalItem
     * @param rowData
     * @param index
     * @returns {*}
     */
    renderModalItem(rowData, index) {
        return <TouchableOpacity
            onPress={() => {
                this.selectWareHouse = rowData;
                this.setState({
                    modalVisible: false,
                });
            }}
            style={{padding: 8}}>
            <Text
                numberOfLines={2}
                style={[StyleUtils.smallFont, StyleUtils.title, {textAlign: null}]}>{rowData.name}</Text>
            <Text
                numberOfLines={2}
                style={[StyleUtils.smallFont, {fontSize: 12, color: 'gray'}]}>{rowData.address}</Text>
        </TouchableOpacity>
    }


    renderRow(rowData, rowID) {
        return (
            <ConfirmOrderListItem
                userData={this.state.userInfo}
                currencyInfo={this.props.currencyInfo}
                dataSource={rowData}/>
        )
    }

    /*从xxx国家发货*/
    goodsCountry(name) {
        let goodsCountry;
        switch (name) {
            case 'RU':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Russia';
                break;
            case 'CN':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' China';
                break;
            case 'KZ':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Kazakhstan';
                break;
            case 'US':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' United States';
                break;
            case 'KG':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Kyrgyzstan';
                break;
            case 'AZ':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Azerbaijan';
                break;
            default:
                goodsCountry = name;
                break
        }
        return goodsCountry;
    }


}
const styles = StyleSheet.create({
    border: {
        padding: 8,
        borderWidth: 1,
        borderColor: '#dee2e4'
    },
    title: {
        fontSize: 16,
        color: '#4e4e4e',
        fontWeight: 'bold',
        textAlign: 'left'
    },
    defaultTv: {
        marginTop: 20,
        fontSize: 18,
        color: 'black',
        textAlign: 'left'

    },
    btnBox: {
        padding: 16,
        paddingTop: 0,
        backgroundColor: 'rgba(255, 255, 255, 0.88)',
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0
    },
});
